package com.xiang.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class ServerInbandHandler2 extends ChannelInboundHandlerAdapter {
    /**
     *  客户端channel初始化完成  相当于init()
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("ServerInbandHandler2 channelActive ...");
        super.channelActive(ctx);
    }

    /**
     * 客户端channel 断开执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("ServerInbandHandler2 channelInactive ...");
        super.channelInactive(ctx);
    }

    /**
     *  读取到客户端channel数据    当channel中数据量大 会分多次读取执行channleRead
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("ServerInbandHandler2 channelRead ...");
//        //读到channel数据  ==》 ServerInbandHandler1中已读出数据，此处无效
//        ByteBuf buf = (ByteBuf) msg;
//        byte[] bytes =new byte[buf.readableBytes()];
//         buf.readBytes(bytes);
//        String result = new String(bytes, StandardCharsets.UTF_8);
//        log.info("读到客户端数据：{}",result);

        //pipeline事件向后传递  channelInbandHandle1 ---> channelInbandHandle2  因为msg被ByteBuf读出，则下一个InbandHandle的msg为空，或自行写入数据
        super.channelRead(ctx, msg);
    }

    /**
     * channel中数据读取完成回调，执行一次。
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("ServerInbandHandler2 channelReadComplete ...");

        //向客户端写数据  《handler1中已写数据》
//        ByteBuf buf = ctx.alloc().buffer().writeBytes(" From Server Message。。。".getBytes(StandardCharsets.UTF_8));
//        ctx.channel().writeAndFlush(buf);

        //事件向后传递  channelInbandHandle1 ---> channelInbandHandle2
        super.channelReadComplete(ctx);
    }

    /**
     * channel执行异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("ServerInbandHandler2 exceptionCaught ...");
        super.exceptionCaught(ctx, cause);
    }
}
